package com.zhangchuchu.neohealth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhangchuchu.neohealth.entity.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {
    //查找好友列表
    @Select("""
    SELECT m1.*
    FROM chat_message m1
    JOIN (
        SELECT sender, MAX(timestamp) AS max_time
        FROM chat_message
        WHERE recipient = #{recipient}
        GROUP BY sender
    ) m2
    ON m1.sender = m2.sender AND m1.timestamp = m2.max_time
    WHERE m1.recipient = #{recipient}
    ORDER BY m1.timestamp DESC
""")
    List<ChatMessage> GetLastMessagesBySender(@Param("recipient") String recipient);
    //查找两个人之间所有的聊天记录
    @Select("""
    SELECT * 
    FROM chat_message
    WHERE (sender = #{sender} AND recipient = #{recipient}) 
       OR (sender = #{recipient} AND recipient = #{sender}) 
    ORDER BY timestamp ASC
""")
    List<ChatMessage> GetChatMessages(@Param("sender") String sender, @Param("recipient") String recipient);
    //已读
    @Update("UPDATE chat_message SET is_read = 1 WHERE sender = #{sender} AND recipient = #{recipient} AND is_read = 0")
    void markMessagesAsRead(@Param("sender") String sender, @Param("recipient") String recipient);
}
